A detailed analysis of dynamics of cosmological models based ongravity is presented. We show that the cosmological equations can be written as a first order autonomous system and analyzed using the standard techniques of dynamical system theory. In absence of perfect fluid matter, we find exact solutions whose behavior and stability are analyzed in terms of the values of the parameter . When matter is introduced, the nature of the (non-minimal) coupling between matter and higher order gravity induces restrictions on the allowed values of . Selecting such intervals of values and following the same procedure used in the vacuum case, we present exact solutions and analyze their stability for a generic value of the parameter . From this analysis emerges the result that for a large set of initial conditions an accelerated expansion is an attractor for the evolution of the cosmology. When matter is present a transient almost-Friedman phase can also be present before the transition to an accelerated expansion.